const nodePath = require('path');
const util = require('util');
const basename = require('path').basename;
const fetch = require('node-fetch');
const chalk = require('chalk');
const exec = util.promisify(require('child_process').exec);
const stat = util.promisify(require('fs').stat);
const readFile = util.promisify(require('fs').readFile);
const {channel, channel_map, baseUrl, randomNum} = require('./config').xingshi;
const {projectName} = require('./config');
const userId = exec('git config user.email').then(({stdout, stderr})=>{
  const user = (stdout||stderr).trim().replace(/@.+$/,'');
  if(!user) throw new Error('git userInfo is null!');
  return user;
});
// 校验path
function formatPath(_path) {
  _path = _path.trim();
  if(!_path) {
    throw new Error('页面路径不能为空');
  } else if (_path.match(/\s|^\//g)) {
    throw new Error('页面路径不能包含特殊字符(不能包含 空格、/开头)！');
  } else if (!_path.match(/\.(html|htm)$/)) {
    throw new Error('页面路径必须以 html、htm 结尾！');
  }
  return _path;
}
async function setHeader() {
  return {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
    "cache-control": "no-cache",
    "content-type": "application/json;charset=UTF-8",
    "pragma": "no-cache",
    "cookie": `leah_auth=${await userId}`
  };
}
// 获取html 代码
async function getHtmlCode(filePath = '') {
  filePath = filePath.trim();
  if(!filePath) {
    throw new Error('html文件路径不能为空');
  } else if (!filePath.match(/\.(html|htm)$/)) {
    throw new Error('html文件路径必须以 .html、.htm 结尾！');
  } else if (await stat(filePath).then((stats) => {
    if(stats.isFile()) return true;
    else throw new Error(`html文件类型不匹配`);
  })) {
    return readFile(filePath, 'utf8');
  }
}
// 星石平台 查找页面数据 如果没有创建则返回null
async function searchPage(_path = '', edit_user = '') {
  edit_user = edit_user.trim();
  const params = {
    channel:channel,
    path:`^${_path}$`,
  };
  const regField = ['channel','path'];
  if(edit_user) {
    params.edit_user = edit_user;
    regField.push('edit_user');
  }
  return fetch(`http://xingshi.woa.com/api/pagelist/list?where=${JSON.stringify(params)}&regField=${regField.toString()}`, {
    "headers": await setHeader(),
    "body": null,
    "method": "GET",
  }).then(res => res.json())
  .then(json => {
    if ( json.code===0 || json.code === 200 ) {
      if (json.data.pagination.total === 0) {
        return null;
      } else {
        return json.data.list[0];
      }
    } else {
      throw new Error(`searchPage: ${json.msg}`);
    }
  });
}
// 星石平台 更新页面 for code
async function uploadPageForCode(remotePath = '', htmlCode = '', filePath = '') {
  if(!htmlCode) throw new Error('HTML内容不能为空');
  remotePath = formatPath(remotePath);
  await fetchHtml(htmlCode);
  await updateList(remotePath, htmlCode);
  const links = await updatePage(remotePath, htmlCode);
  console.log(
    chalk.green('✓ '),
    chalk.cyan(filePath),
    chalk.green('=>'),
    chalk.cyan(links[0]),
    new Date().toLocaleString()
  );
}
// 星石平台 更新页面 for File
async function uploadPageForFile(filePath = '', remotePath = baseUrl.replace(/^\//,'')) {
  const code = await getHtmlCode(filePath);
  const pageName = basename(filePath);
  await uploadPageForCode(
    `${remotePath}${projectName}/${pageName}`,
    code,
    filePath
  );
  // 星石平台 分流页面
  if(randomNum&&pageName==="index.html"){
    console.log(chalk.black.bgYellow(`[分流]`),chalk.yellow(`${pageName}...`));
    for(let i = 0;i<randomNum;i++){
      await uploadPageForCode(
        `${remotePath}_${i}/${projectName}/${pageName}`,
        code,
        filePath
      );
    }
  }
}
async function fetchHtml(htmlCode = '') {
    return await fetch("http://xingshi.woa.com/api/global/fetchHtml", {
      "headers": await setHeader(),
      "body": JSON.stringify({
        html: htmlCode,
        channelDomain: channel_map[channel],
      }),
      "method": "POST",
      "mode": "cors"
    }).then(res => res.json())
    .then(json => {
      if( json.code===0 || json.code === 200 ) {
        return json.data;
      } else {
        throw new Error(`fetchHtml: ${json.msg}`);
      }
    });
}
// 更新html文件
async function updatePage(_path = '', htmlCode = '') {
  return await fetch("http://xingshi.woa.com/api/oct/add_file", {
    "headers": await setHeader(),
    "body": JSON.stringify({
      strData: htmlCode,
      channel: channel,
      path: `/${_path}`,
      fileUrl: `https://${channel_map[channel][0]}/${_path}`
    }),
    "method": "POST",
    "mode": "cors"
    }).then(res => res.json())
    .then(json => {
      if( json.code===0 || json.code === 200 ) {
        return [`https://${channel_map[channel][0]}/${_path}`,...json.data.split(',')];
      } else {
        throw new Error(`updatePage: ${json.msg}`);
      }
    });
}
// 更新星石列表数据
async function updateList(_path = '', htmlCode = '') {
  const pageData = await searchPage(_path);
  const currentTime = new Date();
  if(pageData) {
    // 星石列表中已经存在
    return await fetch("http://xingshi.woa.com/api/pagelist/update", {
      "headers": await setHeader(),
      "body": JSON.stringify({data:{
        channel: pageData.channel,
        name_ch: getTitle(htmlCode) || pageData.name_ch,
        page_type: pageData.page_type,
        path: pageData.path,
        str_data: htmlCode,
        update_time: currentTime,
        edit_user: await userId,
        update_user: await userId,
        url: pageData.url,
        _id: pageData._id,
      }}),
      "method": "POST",
      "mode": "cors"
    }).then(res => res.json())
    .then(json => {
      if ( json.code===0 || json.code === 200 ) {
        return json.data;
      } else {
        throw new Error(`pagelist/update: ${json.msg}`);
      }
    });
  } else {
    return await fetch("http://xingshi.woa.com/api/pagelist/add", {
      "headers": await setHeader(),
      "body": JSON.stringify({data:{
        str_data: htmlCode,
        page_type: 1,
        channel: channel,
        name_ch: getTitle(htmlCode) || _path,
        path: _path,
        edit_user: await userId,
        create_user: await userId,
        update_user: await userId,
        create_time: currentTime,
        update_time: currentTime,
        url: channel_map[channel].map(hostname => {
          return `https://${hostname}/${_path}`
        }).toString(),
      }}),
      "method": "POST",
      "mode": "cors"
    }).then(res => res.json())
    .then(json => {
      if ( json.code===0 || json.code === 200 ) {
        return json.data;
      } else {
        throw new Error(`pagelist/add: ${json.msg}`);
      }
    });
  }
}
function getTitle(htmlCode = '') {
  const title = htmlCode.match(/\<\s*title[^\>]*\>([^\<]*)/);
  if(title){
    return title[1].trim();
  }
  return '';
}
module.exports = uploadPageForFile;